/**
 *******************************************************************************
 * @FileName  : hci_tr_main.c
 * @Author    : GaoQiu
 * @CreateDate: 2020-09-10
 * @Copyright : Copyright(C) GaoQiu
 *              All Rights Reserved.
 *
 *******************************************************************************
 *
 * The information contained herein is confidential and proprietary property of
 * GaoQiu and is available under the terms of Commercial License Agreement
 * between GaoQiu and the licensee in separate contract or the terms desc ribed
 * here-in.
 *
 * This heading MUST NOT be removed from this file.
 *
 * Licensees are granted free, non-transferable use of the information in this
 * file under Mutual Non-Disclosure Agreement. NO WARRENTY of ANY KIND is provided.
 *
 *******************************************************************************
 */
#include "hci_tr_main.h"
#include "hci_tr_api.h"
#include "hci_tr_h4.h"
#include "hci_tr_def.h"
#include "hci_tr_port.h"

#include "stack/controller/lhci_api.h"
#include "stack/ble_config.h"

#include "platform/platform.h"

#if HCI_TR_EN

void HCI_TR_Init(void)
{
#if HCI_TR_MODE == HCI_TR_H4
	HCI_TR_H4Init(LHCI_GetRxCmdFifo(), LHCI_GetRxAclFifo());

#elif HCI_TR_MODE == HCI_TR_H5

#elif HCI_TR_MODE == HCI_TR_USB

#endif
}

static uint8_t uartTxBuf[260] = {0};
void LHCI_TxHandler(void)
{
	/* Check if UART is busy. */
	if(HCI_TR_IsUartBusy()){
		return;
	}

	/* Check if there is data to process. */
	fifo_t *pFifo = LHCI_GetTxAclFifo();
	if(FIFO_Length(pFifo)){
		goto hci_tr_post;
	}

	pFifo = LHCI_GetTxFifo();
	if(FIFO_Length(pFifo)){
		goto hci_tr_post;
	}

	pFifo = LHCI_GetLowPrioTxFifo();
	if(FIFO_Length(pFifo)){
		goto hci_tr_post;
	}
	return; //!!! important

hci_tr_post:
	//if(FIFO_Length(pFifo))
	{
		/* Push data to UART DMA. */
		uint8_t *pBuf = FIFO_GetReadBuf(pFifo);
		if(pBuf)
		{
			uint32_t len = 0;
			uint8_t *p = pBuf;
			BSTREAM_TO_UINT32(len, p);

			memcpy(uartTxBuf, p, len);

			//if(HCI_TR_UartSendDataByDma(pBuf+4, pBuf[0])){
			if(HCI_TR_UartSendDataByDma(uartTxBuf, len)){
				FIFO_MoveToNextReadBuf(pFifo);
			}
		}
		return;
	}
}

/**
 * @brief : HCI transport main loop.
 * @param : none.
 * @param : none.
 */
void HCI_TR_TaskStart(void)
{
#if HCI_TR_MODE == HCI_TR_H4
	/* H4 Transport RX handle */
	//HCI_TR_H4RxHandler();

	LHCI_RxHandler(); /* LHCI RX handle */
	LHCI_TxHandler(); /* LHCI TX handle */

#elif HCI_TR_MODE == HCI_TR_H5

#elif HCI_TR_MODE == HCI_TR_USB

#endif
}

/**
 * @brief : HCI IRQ handler.
 * @param : none.
 * @param : none.
 */
RAM_CODE void HCI_TR_IRQHandler(void)
{
#if HCI_TR_MODE == HCI_TR_H4
	HCI_TR_H4IRQHandler();

#elif HCI_TR_MODE == HCI_TR_H5

#elif HCI_TR_MODE == HCI_TR_USB

#endif
}

#if !UART_TEST_EN
RAM_CODE3 void UART_IRQHandler(void)
{
	HCI_TR_IRQHandler();
}
#endif

#endif
